const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

exports.main = async (event, context) => {
  const { OPENID } = cloud.getWXContext()
  const { action } = event
  
  console.log('🏗️ 施工队伍订单管理云函数调用:', { action, openid: OPENID })
  
  try {
    switch (action) {
      // 获取可接订单列表
      case 'getAvailableOrders':
        return await getAvailableOrders(OPENID, event)
      
      // 接单
      case 'acceptOrder':
        return await acceptOrder(OPENID, event)
      
      // 获取已接订单列表
      case 'getMyOrders':
        return await getMyOrders(OPENID, event)
      
      // 更新订单状态
      case 'updateOrderStatus':
        return await updateOrderStatus(OPENID, event)
      
      // 获取施工队伍信息
      case 'getTeamInfo':
        return await getTeamInfo(OPENID)
      
      // 拒绝订单
      case 'rejectOrder':
        return await rejectOrder(OPENID, event)
      
      // 获取订单详情
      case 'getOrderDetail':
        return await getOrderDetail(OPENID, event)
      
      // 获取订单状态统计
      case 'getOrderStats':
        return await getOrderStats(OPENID, event)
      
      default:
        return {
          success: false,
          error: '未知的操作类型'
        }
    }
  } catch (error) {
    console.error('❌ 施工队伍订单管理失败:', error)
    return {
      success: false,
      error: error.message || '操作失败'
    }
  }
}

// 获取可接订单列表
async function getAvailableOrders(openid, params = {}) {
  console.log('📋 获取可接订单列表 (优化版本 - 显示所有待接单状态)')
  
  try {
    // 首先验证施工队伍资质
    const teamInfo = await getTeamInfo(openid)
    if (!teamInfo.success) {
      return teamInfo
    }
    
    const team = teamInfo.data
    const { page = 1, pageSize = 10, filters = {} } = params
    const { category, urgency, location } = filters
    
    console.log('🔍 查询条件:', { page, pageSize, filters })
    console.log('👥 施工队伍信息:', { 
      id: team._id, 
      name: team.name, 
      specialties: team.specialties 
    })
    
    // 构建查询条件 - 优化为显示所有待接单状态的订单
    let whereCondition = {
      // 所有待接单状态的订单
      status: _.in([
        'pending',        // 待处理
        'waiting_team'    // 等待施工队伍
      ])
    }
    
    // 排除已经被当前施工队伍接单的订单（避免重复接单）
    whereCondition.teamId = _.neq(team._id)
    
    console.log('📋 查询条件详情:', whereCondition)
    
    // 按紧急程度筛选
    if (urgency && urgency !== 'all') {
      whereCondition.urgency = urgency
      console.log('🚨 紧急程度筛选:', urgency)
    }
    
    // 按服务类别筛选（可选）
    if (category && category !== 'all') {
      whereCondition.serviceType = category
      console.log('🏷️ 服务类别筛选:', category)
    }
    
    // 获取总数
    const countResult = await db.collection('orders')
      .where(whereCondition)
      .count()
    
    const totalCount = countResult.total
    console.log(`📊 符合条件的订单总数: ${totalCount}`)
    
    // 获取订单列表
    const skip = (page - 1) * pageSize
    const ordersResult = await db.collection('orders')
      .where(whereCondition)
      .orderBy('createTime', 'desc') // 按创建时间倒序
      .skip(skip)
      .limit(pageSize)
      .get()
    
    // 处理订单数据
    const orders = ordersResult.data.map(order => {
      const publishedHours = Math.floor((Date.now() - new Date(order.createTime).getTime()) / (1000 * 60 * 60))
      
      return {
        ...order,
        // 保持原有的 order.id 字段，不要覆盖为 _id
        serviceTypeLabel: order.serviceTypeLabel || order.serviceType || '通用服务',
        publishedHours: publishedHours,
        // 添加可接单标识
        canAccept: !order.teamId || order.teamId !== team._id,
        // 添加状态显示优化
        statusLabel: getOrderStatusLabel(order.status),
        // 添加紧急程度颜色
        urgencyColor: getUrgencyColor(order.urgency)
      }
    })
    
    console.log(`✅ 获取到 ${orders.length} 个可接订单`)
    orders.forEach(order => {
      console.log(`  📋 ${order.id} - ${order.statusLabel} - ${order.serviceTypeLabel} (${order.publishedHours}小时前)`)
    })
    
    return {
      success: true,
      data: {
        orders: orders,
        total: totalCount,
        hasMore: skip + orders.length < totalCount,
        teamInfo: team
      }
    }
    
  } catch (error) {
    console.error('❌ 获取可接订单列表失败:', error)
    return {
      success: false,
      error: error.message || '获取订单列表失败'
    }
  }
}

// 获取订单状态显示标签
function getOrderStatusLabel(status) {
  const statusMap = {
    'pending': '待处理',
    'waiting_team': '等待接单',
    'accepted': '已接单',
    'team_accepted': '已接单',
    'surveying': '查勘中',
    'designing': '设计中',
    'quoted': '已报价',
    'in_progress': '施工中',
    'testing': '验收中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

// 获取紧急程度颜色
function getUrgencyColor(urgency) {
  const colorMap = {
    'low': '#52c41a',
    'normal': '#1890ff', 
    'high': '#fa8c16',
    'urgent': '#f5222d',
    'emergency': '#f5222d'
  }
  return colorMap[urgency] || '#666666'
}

// 接单
async function acceptOrder(openid, params) {
  console.log('🤝 施工队伍接单')
  
  try {
    const { orderId, estimatedPrice, estimatedDays, notes } = params
    
    if (!orderId) {
      return {
        success: false,
        error: '订单ID不能为空'
      }
    }
    
    if (!estimatedPrice || !estimatedDays) {
      return {
        success: false,
        error: '预估价格和工期不能为空'
      }
    }
    
    // 验证施工队伍资质
    const teamInfo = await getTeamInfo(openid)
    if (!teamInfo.success) {
      return teamInfo
    }
    
    const team = teamInfo.data
    
    // 检查订单状态 - 按业务ID查询
    const orderResult = await db.collection('orders')
      .where({ id: orderId })
      .get()
    
    if (!orderResult.data || orderResult.data.length === 0) {
      return {
        success: false,
        error: '订单不存在'
      }
    }
    
    const order = orderResult.data[0]
    
    console.log('📋 检查订单状态:', {
      orderId: orderId,
      currentStatus: order.status,
      teamId: order.teamId,
      acceptingTeam: team._id
    })
    
    // 检查订单是否可以接单
    const acceptableStatuses = ['pending', 'waiting_team']
    if (!acceptableStatuses.includes(order.status)) {
      return {
        success: false,
        error: `订单状态为"${order.status}"，无法接单`
      }
    }
    
    // 检查是否已被其他施工队伍接单
    if (order.teamId && order.teamId !== team._id) {
      return {
        success: false,
        error: '该订单已被其他施工队伍接单'
      }
    }
    
    // 检查是否已被当前施工队伍接单
    if (order.teamId === team._id) {
      return {
        success: false,
        error: '您已经接过这个订单了'
      }
    }
    
    // 更新订单状态 - 使用数据库_id（设置为新状态系统）
    const updateResult = await db.collection('orders')
      .doc(order._id)
      .update({
        data: {
          status: 'team_accepted',
          teamId: team._id,
          teamName: team.name,
          teamContact: team.contactPerson,
          teamPhone: team.contactPhone,
          estimatedPrice: parseFloat(estimatedPrice),
          estimatedDays: estimatedDays,
          teamNotes: notes || '',
          acceptTime: db.serverDate(),
          updateTime: db.serverDate()
        }
      })
    
    if (updateResult.stats.updated === 0) {
      return {
        success: false,
        error: '接单失败，请重试'
      }
    }
    
    // 记录操作历史
    await db.collection('orderActions').add({
      data: {
        orderId: orderId,
        teamId: team._id,
        action: '接单',
        actionType: 'accept',
        details: `预估价格：¥${estimatedPrice}，预估工期：${estimatedDays}`,
        notes: notes || '',
        operator: team.name,
        createTime: db.serverDate()
      }
    })
    
    // 发送通知给客户
    try {
      await sendOrderNotification(order, team, 'accept', notes)
    } catch (notifyError) {
      console.warn('⚠️ 发送通知失败:', notifyError)
    }
    
    console.log(`✅ 施工队伍 ${team.name} 成功接单 ${orderId}`)
    
    return {
      success: true,
      message: '接单成功'
    }
    
  } catch (error) {
    console.error('❌ 接单失败:', error)
    return {
      success: false,
      error: error.message || '接单失败'
    }
  }
}

// 获取已接订单列表
async function getMyOrders(openid, params = {}) {
  console.log('📜 获取已接订单列表')
  
  try {
    // 验证施工队伍资质
    const teamInfo = await getTeamInfo(openid)
    if (!teamInfo.success) {
      return teamInfo
    }
    
    const team = teamInfo.data
    const { page = 1, pageSize = 10, filters = {} } = params
    const { status } = filters
    
    // 构建查询条件
    let whereCondition = {
      teamId: team._id
    }
    
    // 按状态筛选
    if (status && status !== 'all') {
      whereCondition.status = status
    }
    
    // 获取总数
    const countResult = await db.collection('orders')
      .where(whereCondition)
      .count()
    
    const totalCount = countResult.total
    
    // 获取订单列表
    const skip = (page - 1) * pageSize
    const ordersResult = await db.collection('orders')
      .where(whereCondition)
      .orderBy('acceptTime', 'desc') // 接单时间倒序
      .skip(skip)
      .limit(pageSize)
      .get()
    
    // 处理订单数据
    const orders = ordersResult.data.map(order => ({
      ...order,
      // 保持原有的 order.id 字段，不要覆盖为 _id
      serviceTypeLabel: order.serviceType || '通用服务',
      acceptedHours: order.acceptTime ? 
        Math.floor((Date.now() - new Date(order.acceptTime).getTime()) / (1000 * 60 * 60)) : 0
    }))
    
    console.log(`✅ 获取到 ${orders.length} 个已接订单`)
    
    return {
      success: true,
      data: {
        orders: orders,
        total: totalCount,
        hasMore: skip + orders.length < totalCount
      }
    }
    
  } catch (error) {
    console.error('❌ 获取已接订单列表失败:', error)
    return {
      success: false,
      error: error.message || '获取已接订单列表失败'
    }
  }
}

// 更新订单状态
async function updateOrderStatus(openid, params) {
  console.log('🔄 更新订单状态')
  
  try {
    const { orderId, status, notes } = params
    
    if (!orderId || !status) {
      return {
        success: false,
        error: '订单ID和状态不能为空'
      }
    }
    
    // 验证施工队伍资质
    const teamInfo = await getTeamInfo(openid)
    if (!teamInfo.success) {
      return teamInfo
    }
    
    const team = teamInfo.data
    
    // 检查订单权限 - 按业务ID查询
    const orderResult = await db.collection('orders')
      .where({ id: orderId })
      .get()
    
    if (!orderResult.data || orderResult.data.length === 0) {
      return {
        success: false,
        error: '订单不存在'
      }
    }
    
    const order = orderResult.data[0]
    
    // 检查是否已接单（只有已接单的订单才能更新状态）
    if (order.teamId !== team._id) {
      return {
        success: false,
        error: '只有接单的施工队伍才能更新订单状态'
      }
    }
    
    // 验证状态流转合法性（与用户端状态完全对应）
    const statusFlow = {
      // 新状态系统
      'team_accepted': ['surveying'],            // 已接单 -> 开始查勘
      'surveying': ['designing'],                // 查勘中 -> 开始设计
      'designing': ['quoted'],                   // 设计中 -> 完成报价
      'quoted': ['in_progress'],                 // 已报价 -> 开始施工
      'in_progress': ['testing'],                // 施工中 -> 开始验收
      'testing': ['completed'],                  // 验收中 -> 完成订单
      
      // 兼容旧状态系统
      'accepted': ['surveying'],                 // 已接单 -> 开始查勘
      'confirmed': ['surveying']                 // 已确认 -> 开始查勘
    }
    
    const allowedNextStatuses = statusFlow[order.status] || []
    if (!allowedNextStatuses.includes(status)) {
      return {
        success: false,
        error: `当前状态"${order.status}"不允许更新为"${status}"。允许的状态：${allowedNextStatuses.join(', ')}`
      }
    }
    
    // 更新订单状态
    const updateData = {
      status: status,
      updateTime: db.serverDate()
    }
    
    // 如果是完成状态，记录完成时间
    if (status === 'completed') {
      updateData.completedTime = db.serverDate()
    }
    
    const updateResult = await db.collection('orders')
      .doc(order._id)
      .update({
        data: updateData
      })
    
    if (updateResult.stats.updated === 0) {
      return {
        success: false,
        error: '状态更新失败，请重试'
      }
    }
    
    // 记录操作历史
    const statusNames = {
      'surveying': '开始查勘',
      'designing': '开始设计',
      'quoted': '完成报价',
      'in_progress': '开始施工',
      'testing': '开始验收',
      'completed': '完成订单'
    }
    
    await db.collection('orderActions').add({
      data: {
        orderId: orderId,
        teamId: team._id,
        action: statusNames[status] || '更新状态',
        actionType: 'status_update',
        details: `状态更新为：${statusNames[status] || status}`,
        notes: notes || '',
        operator: team.name,
        createTime: db.serverDate()
      }
    })
    
    // 发送通知给客户
    try {
      await sendOrderNotification(order, team, 'status_update', notes, status)
    } catch (notifyError) {
      console.warn('⚠️ 发送通知失败:', notifyError)
    }
    
    console.log(`✅ 订单 ${orderId} 状态更新为 ${status}`)
    
    return {
      success: true,
      message: '状态更新成功'
    }
    
  } catch (error) {
    console.error('❌ 更新订单状态失败:', error)
    return {
      success: false,
      error: error.message || '状态更新失败'
    }
  }
}

// 获取施工队伍信息
async function getTeamInfo(openid) {
  console.log('👥 获取施工队伍信息 (区分审核状态和订单状态)', { openid })
  
  try {
    // 查询施工队伍信息 - 使用正确的集合名称 construction_teams
    const teamResult = await db.collection('construction_teams')
      .where({
        openid: openid
      })
      .get()
    
    console.log(`🔍 查询 construction_teams 集合，找到 ${teamResult.data.length} 条记录`)
    
    if (teamResult.data.length === 0) {
      console.log('❌ 在 construction_teams 集合中未找到记录')
      return {
        success: false,
        error: '您还没有注册施工队伍，请先完成注册'
      }
    }
    
    const team = teamResult.data[0]
    console.log('📋 施工队伍详细信息:', {
      _id: team._id,
      name: team.name,
      auditStatus: team.auditStatus,  // 审核状态
      status: team.status,            // 订单状态 (busy=有订单)
      canReceiveOrders: team.canReceiveOrders,
      specialties: team.specialties || []
    })
    
    // 1. 检查审核状态 - 使用 auditStatus 字段
    const approvedAuditStatuses = [
      'approved', 'passed', '通过', '审核通过', 'active', 
      '已通过', 'accepted', 'success', '有效', 'valid'
    ]
    
    const isAuditApproved = approvedAuditStatuses.includes(team.auditStatus)
    
    console.log(`📊 审核状态检查 (auditStatus): "${team.auditStatus}" -> ${isAuditApproved ? '✅ 审核通过' : '❌ 审核未通过'}`)
    console.log(`📝 支持的审核状态值: ${approvedAuditStatuses.join(', ')}`)
    
    // 如果auditStatus字段为空或未定义，也允许通过（宽松模式）
    if (!isAuditApproved && team.auditStatus && team.auditStatus.trim() !== '') {
      return {
        success: false,
        error: `您的施工队伍审核状态为"${team.auditStatus}"，尚未通过审核。请联系管理员确认审核状态。`
      }
    }
    
    // 2. 检查订单状态 - 使用 status 字段 (这个不影响是否能接单，只是显示当前状态)
    console.log(`📋 订单状态 (status): "${team.status}" ${team.status === 'busy' ? '(当前有订单在进行)' : '(当前空闲)'}`)
    
    // 3. 检查是否可以接单
    if (team.canReceiveOrders === false) {
      return {
        success: false,
        error: '您的施工队伍暂时无法接单，请联系管理员'
      }
    }
    
    console.log(`✅ 权限验证通过: ${team.name}`)
    console.log(`   - 审核状态: ${team.auditStatus || '未设置'} ✅`)
    console.log(`   - 订单状态: ${team.status || '空闲'} (${team.status === 'busy' ? '繁忙' : '可接单'})`)
    
    return {
      success: true,
      data: {
        ...team,
        canReceiveOrders: true,
        // 添加状态说明
        auditStatusText: isAuditApproved ? '审核通过' : '审核中',
        orderStatusText: team.status === 'busy' ? '当前有订单' : '可接新订单'
      }
    }
    
  } catch (error) {
    console.error('❌ 获取施工队伍信息失败:', error)
    return {
      success: false,
      error: `获取施工队伍信息失败: ${error.message}`
    }
  }
}

// 拒绝订单
async function rejectOrder(openid, params) {
  console.log('❌ 拒绝订单')
  
  try {
    const { orderId, reason } = params
    
    if (!orderId || !reason) {
      return {
        success: false,
        error: '订单ID和拒绝原因不能为空'
      }
    }
    
    // 验证施工队伍资质
    const teamInfo = await getTeamInfo(openid)
    if (!teamInfo.success) {
      return teamInfo
    }
    
    const team = teamInfo.data
    
    // 检查订单状态 - 按业务ID查询
    const orderResult = await db.collection('orders')
      .where({ id: orderId })
      .get()
    
    if (!orderResult.data || orderResult.data.length === 0) {
      return {
        success: false,
        error: '订单不存在'
      }
    }
    
    const order = orderResult.data[0]
    
    if (order.status !== 'waiting_team') {
      return {
        success: false,
        error: '该订单状态已变更，无法拒绝'
      }
    }
    
    // 记录拒绝信息到订单拒绝记录表
    await db.collection('orderRejects').add({
      data: {
        orderId: orderId,
        teamId: team._id,
        teamName: team.name,
        reason: reason,
        rejectTime: db.serverDate()
      }
    })
    
    // 记录操作历史
    await db.collection('orderActions').add({
      data: {
        orderId: orderId,
        teamId: team._id,
        action: '拒绝订单',
        actionType: 'reject',
        details: `拒绝原因：${reason}`,
        notes: reason,
        operator: team.name,
        createTime: db.serverDate()
      }
    })
    
    console.log(`✅ 施工队伍 ${team.name} 拒绝订单 ${orderId}`)
    
    return {
      success: true,
      message: '已拒绝订单'
    }
    
  } catch (error) {
    console.error('❌ 拒绝订单失败:', error)
    return {
      success: false,
      error: error.message || '拒绝订单失败'
    }
  }
}

// 获取订单详情
async function getOrderDetail(openid, params) {
  console.log('📄 获取订单详情')
  
  try {
    const { orderId } = params
    
    if (!orderId) {
      return {
        success: false,
        error: '订单ID不能为空'
      }
    }
    
    // 验证施工队伍资质
    const teamInfo = await getTeamInfo(openid)
    if (!teamInfo.success) {
      return teamInfo
    }
    
    const team = teamInfo.data
    
    // 获取订单详情 - 按业务ID查询
    const orderResult = await db.collection('orders')
      .where({ id: orderId })
      .get()
    
    if (!orderResult.data || orderResult.data.length === 0) {
      return {
        success: false,
        error: '订单不存在'
      }
    }
    
    const order = orderResult.data[0]
    
    // 检查权限（可接单状态的订单或当前队伍已接单的订单才能查看详情）
    const viewableStatuses = ['pending', 'waiting_team']
    const isViewableOrder = viewableStatuses.includes(order.status) || order.teamId === team._id
    
    if (!isViewableOrder) {
      return {
        success: false,
        error: '您没有权限查看此订单详情'
      }
    }
    
    // 获取操作历史
    const actionsResult = await db.collection('orderActions')
      .where({
        orderId: orderId
      })
      .orderBy('createTime', 'desc')
      .get()
    
    console.log(`✅ 获取订单详情成功: ${orderId}`)
    
    return {
      success: true,
      data: {
        order: order,
        teamInfo: team,
        actionHistory: actionsResult.data
      }
    }
    
  } catch (error) {
    console.error('❌ 获取订单详情失败:', error)
    return {
      success: false,
      error: error.message || '获取订单详情失败'
    }
  }
}

// 发送订单通知
async function sendOrderNotification(order, team, action, notes, newStatus) {
  console.log('📱 发送订单通知')
  
  try {
    // 这里可以集成微信消息推送、短信通知等
    // 暂时只记录日志
    
    const messages = {
      'accept': `您的订单已被施工队伍"${team.name}"接单`,
      'status_update': `您的订单状态已更新`,
      'reject': `您的订单被拒绝`
    }
    
    console.log(`📧 通知内容: ${messages[action]}`)
    console.log(`📧 订单ID: ${order._id}`)
    console.log(`📧 施工队伍: ${team.name}`)
    console.log(`📧 备注: ${notes || '无'}`)
    
    return {
      success: true,
      message: '通知发送成功'
    }
    
  } catch (error) {
    console.error('❌ 发送通知失败:', error)
    throw error
  }
}

// 获取订单状态统计
async function getOrderStats(openid, params = {}) {
  console.log('📊 获取订单状态统计')
  
  try {
    // 首先验证施工队伍资质
    const teamInfo = await getTeamInfo(openid)
    if (!teamInfo.success) {
      return teamInfo
    }
    
    const team = teamInfo.data
    console.log('👥 获取统计数据，施工队伍:', team.name)
    
    // 定义需要统计的状态（与用户端标签页完全对应）
    const statusesToCount = [
      'waiting_team',   // 待接单（仅对可接订单有效）
      'team_accepted',  // 已接单
      'surveying',      // 查勘中  
      'designing',      // 设计中
      'quoted',         // 已报价
      'in_progress',    // 施工中
      'testing',        // 验收中
      'completed',      // 已完成
      'cancelled'       // 已取消
    ]
    
    // 并行查询每个状态的订单数量
    const statsPromises = statusesToCount.map(async (status) => {
      let result
      
      if (status === 'waiting_team') {
        // 待接单状态：统计所有等待接单的订单（不限制teamId）
        result = await db.collection('orders').where({
          status: _.in(['pending', 'waiting_team'])
        }).count()
      } else {
        // 其他状态：统计当前施工队伍的订单（包含兼容状态）
        let statusesToQuery = [status]
        
        // 添加兼容状态映射
        if (status === 'team_accepted') {
          statusesToQuery = ['team_accepted', 'accepted', 'confirmed']
        }
        
        result = await db.collection('orders').where({
          teamId: team._id,
          status: _.in(statusesToQuery)
        }).count()
      }
      
      return {
        status: status,
        count: result.total
      }
    })
    
    // 等待所有查询完成
    const statsResults = await Promise.all(statsPromises)
    
    // 构建统计对象
    const stats = {}
    let totalMyOrders = 0
    
    statsResults.forEach(result => {
      stats[result.status] = result.count
      // waiting_team 不计入 totalMyOrders（这是可接订单，不是已接订单）
      if (result.status !== 'waiting_team') {
        totalMyOrders += result.count
      }
    })
    
    // 查询可接订单数量
    const availableResult = await db.collection('orders').where({
      status: _.in(['pending', 'waiting_team']),
      teamId: _.neq(team._id)  // 排除已被当前队伍接单的
    }).count()
    
    stats.available = availableResult.total
    stats.totalMyOrders = totalMyOrders
    
    console.log('📊 统计结果:', stats)
    
    return {
      success: true,
      data: stats
    }
    
  } catch (error) {
    console.error('❌ 获取订单状态统计失败:', error)
    return {
      success: false,
      error: error.message || '获取统计失败'
    }
  }
} 